package broker

import (
	"manager/bll"
	"manager/lib/trace_log"
	SignalPo "manager/model/signal"
	"manager/utils"
	"manager/utils/goroutine_pool"
	"sync"
	"time"
)

var CornTask = NewCronTask()

// cronTask 定时任务
type cronTask struct {
	OnlineDeviceMap sync.Map
}

// NewCronTask 创建定时任务
func NewCronTask() *cronTask {
	task := &cronTask{
		OnlineDeviceMap: sync.Map{},
	}

	go task.OnPolling()
	return task
}

// IsExist 判断设备是否存在
func (t *cronTask) IsExist(sn string) bool {
	_, ok := t.OnlineDeviceMap.Load(sn)
	return ok
}

// AddOnlineDevice 添加在线设备
func (t *cronTask) AddOnlineDevice(sn string) {
	t.OnlineDeviceMap.Store(sn, time.Now().Unix())
}

// RemoveOnlineDevice 移除在线设备
func (t *cronTask) RemoveOnlineDevice(sn string) {
	t.OnlineDeviceMap.Delete(sn)
}

// ResetOnlineDevice 重置在线设备
func (t *cronTask) ResetOnlineDevice(sn string) {
	t.OnlineDeviceMap.Store(sn, time.Now().Unix())
}

func (t *cronTask) OnPolling() {
	defer utils.ExceptionCatch()
	ticker := time.NewTicker(time.Second * 60)
	for {
		select {
		case <-ticker.C:
			t.OnlineDeviceMap.Range(func(key, value interface{}) bool {
				// 10分钟查一次电池电量
				if time.Now().Unix()-value.(int64) > 600 {
					t.ResetOnlineDevice(key.(string))
					goroutine_pool.GetPoolV2("cronTask").Push(key.(string), func(data interface{}) error {
						trace_log.DebugLogger(data.(string), "cronTask 10分钟查询电量和位置")
						bll.SignalV2.GetMsgFromDevice(data.(string), &SignalPo.GetMessageReq{
							Cmd: "Battery",
						})

						bll.SignalV2.GetMsgFromDevice(data.(string), &SignalPo.GetMessageReq{
							Cmd: "Location",
						})
						return nil
					})
				}
				return true
			})
		}
	}
}
